<!DOCTYPE html>
<html
        lang="zh"
        xmlns:th="http://www.thymeleaf.org"
        xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
>
<head>
    <th:block th:insert="~{include :: header('设备信息列表')}"/>
    <style>
        .mqtt-test-panel {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 800px;
            max-width: 90%;
            background: #fff;
            border-radius: 4px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 10000;
            display: none;
        }

        .mqtt-test-panel .panel-header {
            padding: 15px;
            border-bottom: 1px solid #eee;
            font-weight: bold;
            font-size: 18px;
        }

        .mqtt-test-panel .panel-body {
            padding: 20px;
        }

        .mqtt-test-panel .form-group {
            margin-bottom: 15px;
        }

        .mqtt-test-panel .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .mqtt-test-panel .form-group input,
        .mqtt-test-panel .form-group textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }

        .mqtt-test-panel .form-group textarea {
            min-height: 120px;
            resize: vertical;
        }

        .mqtt-test-panel .panel-footer {
            padding: 15px;
            border-top: 1px solid #eee;
            text-align: right;
        }

        .mqtt-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 9999;
            display: none;
        }

        .mqtt-messages {
            max-height: 200px;
            min-height: 200px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            background: #f9f9f9;
            margin-top: 10px;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            white-space: pre-wrap;
        }

        .message-item {
            margin-bottom: 5px;
            padding: 5px;
            border-bottom: 1px solid #eee;
        }

        .message-item:last-child {
            border-bottom: none;
        }

        .message-timestamp {
            color: #666;
            font-size: 12px;
        }

        .message-content {
            margin-top: 3px;
        }
    </style>
</head>
<body class="gray-bg">
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <form id="formId">
                <div class="select-list">
                    <ul>
                        <li>
                            <label>设备名称：</label>
                            <input type="text" name="devName"/>
                        </li>
                        <li>
                            <label>设备编号：</label>
                            <input type="text" name="devNumber"/>
                        </li>
                        <li>
                            <label>位置：</label>
                            <input type="text" name="currentLocation"/>
                        </li>
                        <li>
                            <label>纬度：</label>
                            <input type="text" name="latitude"/>
                        </li>
                        <li>
                            <label>经度：</label>
                            <input type="text" name="longitude"/>
                        </li>
                        <li>
                            <a
                                    class="btn btn-primary btn-rounded btn-sm"
                                    onclick="$.table.search()"
                            ><i class="fa fa-search"></i>&nbsp;搜索</a
                            >
                            <a
                                    class="btn btn-warning btn-rounded btn-sm"
                                    onclick="$.form.reset()"
                            ><i class="fa fa-refresh"></i>&nbsp;重置</a
                            >
                        </li>
                    </ul>
                </div>
            </form>
        </div>

        <div class="btn-group-sm" id="toolbar" role="group">
            <a
                    class="btn btn-success"
                    onclick="$.operate.add()"
                    shiro:hasPermission="deviceManager:device:add"
            >
                <i class="fa fa-plus"></i> 添加
            </a>
            <a
                    class="btn btn-primary single disabled"
                    onclick="$.operate.edit()"
                    shiro:hasPermission="deviceManager:device:edit"
            >
                <i class="fa fa-edit"></i> 修改
            </a>
            <a
                    class="btn btn-danger multiple disabled"
                    onclick="$.operate.removeAll()"
                    shiro:hasPermission="deviceManager:device:remove"
            >
                <i class="fa fa-remove"></i> 删除
            </a>
            <a
                    class="btn btn-warning"
                    onclick="$.table.exportExcel()"
                    shiro:hasPermission="deviceManager:device:export"
            >
                <i class="fa fa-download"></i> 导出
            </a>
        </div>
        <div class="col-sm-12 select-table table-striped">
            <table id="bootstrap-table"></table>
        </div>
    </div>
</div>

<!-- MQTT测试弹窗 -->
<div class="mqtt-overlay" id="mqttOverlay"></div>
<div class="mqtt-test-panel" id="mqttTestPanel">
    <div class="panel-header">MQTT测试</div>
    <div class="panel-body">
        <input type="hidden" id="deviceId" />
        <div class="form-group">
            <label for="mqttTopic">发布主题 (Topic):</label>
            <input type="text" id="mqttTopic" placeholder="请输入MQTT发布主题，例如: device/123/control" />
        </div>
        <div class="form-group">
            <label for="mqttPublish">发送内容:</label>
            <textarea id="mqttPublish" placeholder="请输入要发送的内容"></textarea>
        </div>
        <div class="form-group">
            <button class="btn btn-primary" onclick="publishMqtt()"><i class="fa fa-send"></i> 发送消息</button>
        </div>
        <div class="form-group">
            <label for="mqttSubscribe">订阅主题:</label>
            <input type="text" id="mqttSubscribe" readonly />
        </div>
        <div class="form-group">
            <label>接收内容:</label>
            <div class="mqtt-messages" id="receivedMessages"></div>
        </div>
    </div>
    <div class="panel-footer">
        <button class="btn btn-default" onclick="closeMqttTest()"><i class="fa fa-close"></i> 关闭</button>
    </div>
</div>

<th:block th:insert="~{include :: footer}"/>
<script th:src="@{/js/websocket-device.js}"></script>
<script th:inline="javascript">
    var editFlag = [[${@permission.hasPermi('deviceManager:device:edit')}]];
    var removeFlag = [[${@permission.hasPermi('deviceManager:device:remove')}]];
    var prefix = ctx + "deviceManager/device";

    $(function () {
        var options = {
            url: prefix + "/list",
            createUrl: prefix + "/add",
            updateUrl: prefix + "/edit/{id}",
            removeUrl: prefix + "/remove",
            exportUrl: prefix + "/export",
            modalName: "设备信息",
            uniqueId: 'devId', // 确保唯一 ID 可定位行
            columns: [{
                checkbox: true
            },
                {
                    field: 'devId',
                    title: '设备ID',
                    visible: false
                },
                {
                    field: 'devName',
                    title: '设备名称'
                },
                {
                    field: 'devNumber',
                    title: '设备编号'
                },
                {
                    field: 'status',
                    title: '设备状态',
                    formatter: function (value, row, index) {
                        var statusText = '未知状态';
                        var statusColor = 'gray';
                        switch (value) {
                            case '0':
                                statusText = '离线';
                                statusColor = 'gray';
                                break;
                            case '1':
                                statusText = '在线';
                                statusColor = 'green';
                                break;
                            case '2':
                                statusText = '异常';
                                statusColor = 'red';
                                break;
                            case '3':
                                statusText = '维护中';
                                statusColor = 'orange';
                                break;
                            case '4':
                                statusText = '待配置';
                                statusColor = '#800080'; // 紫色
                                break;
                        }

                        return '<span style="color: ' + statusColor + '; font-weight: bold;">' + statusText + '</span>';
                    }
                },
                {
                    field: 'voltage',
                    title: '设备电压'
                },
                {
                    field: 'currentLocation',
                    title: '地址'
                },
                {
                    field: 'latitude',
                    title: '纬度'
                },
                {
                    field: 'longitude',
                    title: '经度'
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function(value, row, index) {
                        var actions = [];

                        actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="$.operate.edit(\'' + row.devId + '\')"><i class="fa fa-edit"></i>编辑</a> ');
                        actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.devId + '\')"><i class="fa fa-remove"></i>删除</a>');
                        actions.push('<a class="btn btn-info btn-xs" href="javascript:void(0)" onclick="testMqtt(\'' + row.devId + '\', \'' + (row.publish || '') + '\', \'' + (row.subscribe || '') + '\')"><i class="fa fa-send"></i>MQTT测试</a>');
                        return actions.join('');
                    }
                }]
        };
        $.table.init(options);

        // =============================
        // 🚀 WebSocket 实时更新设备状态
        // =============================
        const unsubscribe = window.WebSocketDevice.addListener(function (message) {
            console.log('WebSocketDevice:', message)
            // 校验消息
            if (!message || typeof message !== 'object' || !message.devNumber || !message.type) {
                return;
            }

            const devNumber = message.devNumber;
            const type = message.type;
            const $table = $('#bootstrap-table');

            // ✅ 直接使用 bootstrap-table 原生 API
            const allRows = $table.bootstrapTable('getData');
            const targetRow = allRows.find(row => row.devNumber === devNumber);

            if (!targetRow) {
                console.debug(`设备编号 ${devNumber} 不在当前列表中`);
                return;
            }

            console.log(`设备编号 ${devNumber} 的状态已更新为 ${type}`)
            // 根据消息类型处理
            switch (type) {
                case 'status':
                    let status = message.data.status ? '1' : '0';
                    targetRow.status = status
                    // 处理设备在线状态消息
                    // 使用原生 updateByUniqueId（基于 uniqueId）
                    $table.bootstrapTable('updateByUniqueId', {
                        id: targetRow.devId,
                        row: targetRow
                    });
                    console.log(`✅ 已更新设备 [${devNumber}] 状态为 ${status === '1' ? '在线' : '离线'}`);
                    break;

                case 'abnormal':
                    // 处理设备异常消息
                    targetRow.status = '2'; // 用'2'表示异常状态
                    $table.bootstrapTable('updateByUniqueId', {
                        id: targetRow.devId,
                        row: targetRow
                    });
                    console.log(`⚠️ 设备 [${devNumber}] 异常:`, message.data);

                    // 显示异常信息
                    if (message.data && message.data.message) {
                        // 尝试解析嵌套的JSON消息

                        try {
                            const innerMessage = message.data;
                            $.modal.alertWarning(`设备 [${devNumber}] : ${innerMessage.workStatus} <br> 详细信息: ${innerMessage.message}`);
                        } catch (e) {
                            // 如果解析失败，直接显示原始消息
                            $.modal.alertWarning(`异常 [${devNumber}] : ${message.data}`);
                        }
                    } else {
                        $.modal.alertWarning(`设备[${devNumber}] 异常: ${message.data.workStatus}`);
                    }
                    break;

                case 'data':
                    // 处理设备数据消息，目前只记录日志
                    targetRow.voltage = message.data.voltage;
                    $table.bootstrapTable('updateByUniqueId', {
                        id: targetRow.devId,
                        row: targetRow
                    });
                    console.log(`📊 设备 [${devNumber}] 数据:`, message.data);
                    break;

                default:
                    console.warn(`未知消息类型: ${type}`);
            }
        });

        // 页面卸载时取消监听（可选）
        $(window).on('beforeunload', function () {
            unsubscribe && unsubscribe();
        });
    });

    // MQTT测试功能
    function testMqtt(deviceId, publishTopic, subscribeTopic) {
        $('#deviceId').val(deviceId);
        $('#mqttSubscribe').val(subscribeTopic || '');
        $('#mqttTestPanel').show();
        $('#mqttOverlay').show();
        $('#receivedMessages').empty();
        
        // 默认发布主题设置为设备发布主题
        if (publishTopic) {
            $('#mqttTopic').val(publishTopic);
        }
        
        // 监听WebSocket消息并显示
        const unsubscribe = window.WebSocketDevice.addListener(function(message) {
            // 只显示与当前设备相关的消息
            if (message && typeof message === 'object' && message.devNumber === (subscribeTopic || '')) {
                // 过滤掉type为status的消息
                if (message.type === 'status' || message.type === 'abnormal') {
                    return;
                }
                
                var timestamp = new Date().toLocaleString();
                var messageItem = '<div class="message-item">' +
                                  '<div class="message-timestamp">接收时间: ' + timestamp + '</div>';
                
                if (message.type === 'data') {
                    // 处理嵌套的JSON字符串
                    var displayData = message.data;
                    if (displayData && typeof displayData === 'object' && displayData.content) {
                        // 检查content是否为JSON字符串
                        if (typeof displayData.content === 'string') {
                            try {
                                // 尝试解析嵌套的JSON字符串
                                var parsedContent = JSON.parse(displayData.content);
                                displayData = {
                                    ...displayData,
                                    content: parsedContent
                                };
                            } catch (e) {
                                // 解析失败，保持原样
                            }
                        }
                    }
                    
                    // 格式化显示数据内容，去除转义字符
                    var formattedData = JSON.stringify(displayData, null, 2);
                    formattedData = formattedData.replace(/\\r\\n/g, '').replace(/\\n/g, '').replace(/\\t/g, '');
                    messageItem += '<div class="message-content"><strong>数据内容:</strong> <pre>' + formattedData + '</pre></div>';
                } else {
                    // 处理消息内容，特别是message字段中的转义字符
                    var displayData = typeof message.data === 'object' ? {...message.data} : message.data;
                    
                    // 对abnormal类型消息进行特殊处理
                    if (message.type === 'abnormal' && typeof displayData === 'object' && displayData.message) {
                        if (typeof displayData.message === 'string') {
                            try {
                                // 尝试解析嵌套的JSON字符串
                                var parsedMessage = JSON.parse(displayData.message);
                                displayData = {
                                    ...displayData,
                                    message: parsedMessage
                                };
                            } catch (e) {
                                // 解析失败，去除转义字符
                                displayData.message = displayData.message.replace(/\\r\\n/g, '').replace(/\\n/g, '').replace(/\\t/g, '');
                            }
                        } else {
                            // 如果message不是字符串，去除转义字符
                            displayData.message = displayData.message.replace(/\\r\\n/g, '').replace(/\\n/g, '').replace(/\\t/g, '');
                        }
                    }
                    // 对其他类型消息中的message字段进行处理
                    else if (typeof displayData === 'object' && displayData.message && typeof displayData.message === 'string') {
                        // 去除message字段中的转义字符
                        displayData.message = displayData.message.replace(/\\r\\n/g, '').replace(/\\n/g, '').replace(/\\t/g, '');
                    }
                    
                    // 格式化显示消息内容，去除转义字符
                    var formattedMessage = JSON.stringify(displayData, null, 2);
                    formattedMessage = formattedMessage.replace(/\\r\\n/g, '').replace(/\\n/g, '').replace(/\\t/g, '');
                    messageItem += '<div class="message-content"><strong>消息类型:</strong> ' + message.type + '</div>' +
                                   '<div class="message-content"><strong>消息内容:</strong> <pre>' + formattedMessage + '</pre></div>';
                }
                
                messageItem += '</div>';
                $('#receivedMessages').append(messageItem);
                $('#receivedMessages').scrollTop($('#receivedMessages')[0].scrollHeight);
            }
        });
        
        // 在关闭测试面板时取消监听
        $('#mqttTestPanel').off('close.mqttTest').on('close.mqttTest', function() {
            if (unsubscribe && typeof unsubscribe === 'function') {
                unsubscribe();
            }
        });
    }

    function closeMqttTest() {
        $('#mqttTestPanel').hide();
        $('#mqttOverlay').hide();
        // 触发关闭事件以取消WebSocket监听
        $('#mqttTestPanel').trigger('close.mqttTest');
    }

    function publishMqtt() {
        var deviceId = $('#deviceId').val();
        var topic = $('#mqttTopic').val();
        var message = $('#mqttPublish').val();

        if (!topic) {
            $.modal.alertWarning('请输入主题');
            return;
        }

        if (!message) {
            $.modal.alertWarning('请输入要发送的内容');
            return;
        }

        // 调用后端API发送MQTT消息
        $.ajax({
            url: prefix + "/publish",
            type: "POST",
            data: {
                "topic": topic,
                "message": message
            },
            success: function (result) {
                if (result.code == 0) {
                    var timestamp = new Date().toLocaleString();
                    var messageItem = '<div class="message-item">' +
                        '<div class="message-timestamp">发送时间: ' + timestamp + '</div>' +
                        '<div class="message-content"><strong>主题:</strong> ' + topic + '</div>' +
                        '<div class="message-content"><strong>内容:</strong> ' + message + '</div>' +
                        '<div class="message-content"><strong>状态:</strong> 发送成功</div>' +
                        '</div>';
                    $('#receivedMessages').append(messageItem);
                    $('#receivedMessages').scrollTop($('#receivedMessages')[0].scrollHeight);

                    // 清空发送内容
                    $('#mqttPublish').val('');
                } else {
                    $.modal.alertError('消息发送失败: ' + result.msg);
                }
            },
            error: function () {
                $.modal.alertError('请求发送失败');
            }
        });
    }

    // 点击遮罩层关闭弹窗
    $('#mqttOverlay').click(function () {
        closeMqttTest();
    });
</script>
</body>
</html>